package com.ddstation.exchange.task;


import com.ddstation.common.property.EnvironmentEnum;
import com.ddstation.common.property.EnvironmentProperties;
import com.ddstation.common.util.AliCloudOssUtil;
import com.ddstation.common.util.CheckUtil;
import com.ddstation.common.util.HttpClientUtil;
import com.ddstation.crm.institution.entity.DtHealthManageInstitutionDoctorEntity;
import com.ddstation.crm.institution.entity.DtHealthManageInstitutionEntity;
import com.ddstation.crm.institution.mapper.DtHealthManageInstitutionDoctorMapper;
import com.ddstation.crm.institution.mapper.DtHealthManageInstitutionMapper;
import com.ddstation.crm.outpatient.entity.*;
import com.ddstation.crm.outpatient.mapper.*;
import com.ddstation.crud.entity.DtInvsManageInstitutionEntity;
import com.ddstation.crud.mapper.DtInvsManageInstitutionMapper;
import com.ddstation.doctor.entity.DdDoctorEntity;
import com.ddstation.doctor.mapper.DdDoctorMapper;
import com.ddstation.exam.entity.*;
import com.ddstation.exam.mapper.*;
import com.ddstation.exchange.entity.AllTypesTableEntity;
import com.ddstation.exchange.entity.DtHealthDataDiagnosisEntity;
import com.ddstation.exchange.mapper.AllTypesTableMapper;
import com.ddstation.exchange.mapper.DtHealthDataDiagnosisEntityMapper;
import com.ddstation.exchange.model.out.*;
import com.ddstation.exchange.service.out.DataFromInvsWebService;
import com.ddstation.lab.entity.DtHealthDataMedicalTest;
import com.ddstation.lab.mapper.DtHealthDataMedicalTestMapper;
import com.ddstation.user.health_file.entity.DdRecordBaseInfoEntity;
import com.ddstation.user.health_file.mapper.DdRecordBaseInfoMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import tk.mybatis.spring.annotation.MapperScan;

import javax.annotation.Resource;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;


@Component
@MapperScan({"com.ddstation.crm.outpatient.mapper","com.ddstation.lab.mapper","com.ddstation.exam.mapper","com.ddstation.doctor.mapper","com.ddstation.exchange.mapper"})
public class PatientMedicalFromHisTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(PatientMedicalFromHisTask.class);

    @Resource
    DtHealthDataOutpatientMedicalMapper dtHealthDataOutpatientMedicalMapper;
    @Resource
    private DtHealthDataWestPrescriptionMapper dtHealthDataWestPrescriptionMapper;
    @Resource
    private DtHealthDataMedicalTestMapper dtHealthDataMedicalTestMapper;
    @Resource
    private DtInvsExamReportResultMapper dtInvsExamReportResultMapper;
    @Resource
    private CyhisBaseDrugMapper cyhisBaseDrugMapper;
    @Resource
    private DdDoctorMapper ddDoctorMapper;
    @Resource
    private DtHealthManageInstitutionDoctorMapper dtHealthManageInstitutionDoctorMapper;
    @Resource
    private DtHealthDataDiagnosisEntityMapper dtHealthDataDiagnosisEntityMapper;
    @Resource
    private DdRecordBaseInfoMapper ddRecordBaseInfoMapper;
    @Resource
    private MaInvsDataExchangeStatisticsMapper exchangeStatisticsMapper;


//    String REQUEST_IP = "http://www.lawjj.cn:8282/services";//请求IP
    String REQUEST_IP = "http://10.33.169.160:8282/services";//请求IP
    String INVS_MANAGE_INSTITUTION_ID = "00000001";//卫生监督所ID
    String INVS_IP = "10.33.188.107";//获取授权IP
    String INVS_NAME = "WSJDQZT";//获取授权名称

    /**
     * 获取病例数据
     */
    public void task() {
        //获取结束时间(当前时间)
        Calendar beforeTime = Calendar.getInstance();
        Calendar endTime = Calendar.getInstance();

        //获取开始时间(15分钟前)
        beforeTime.add(Calendar.HOUR, -72);// 24分钟之前的时间
        endTime.add(Calendar.HOUR, -60);
        Date beforeD = beforeTime.getTime();
        Date endD = endTime.getTime();
        String startDate = new SimpleDateFormat("yyyy-MM-dd").format(beforeD) + "T"
                + new SimpleDateFormat("HH:mm:ss").format(beforeD) + "+08:00";
        String endDate = new SimpleDateFormat("yyyy-MM-dd").format(endD) + "T"
                + new SimpleDateFormat("HH:mm:ss").format(endD) + "+08:00";
//        taskFunction("2020-05-28T12:00:00+08:00","2020-05-29T15:00:00+08:00");
        taskFunction(startDate,endDate);
    }


    public void taskFunction(String startDate,String endDate){
        //获取身份标识uuid
        String uuid = getUuid();
        if(uuid != null){
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            //获取全部机构
            List<DtInvsManageInstitutionEntity> institutionList = dtInvsManageInstitutionMapper.selectInvsInstitutionInfoSql(INVS_MANAGE_INSTITUTION_ID);//获取某个地区所有机构
            //遍历机构获取数据
            for(DtInvsManageInstitutionEntity institution:institutionList) {
                String institutionId = institution.getId();
                //2.1.1.	获取门诊信息列表
                JSONObject medicalRecordPageListInJson = new JSONObject();
                medicalRecordPageListInJson.put("organ_code",institutionId);//机构编码
                medicalRecordPageListInJson.put("sqm",uuid);//权限标识
                medicalRecordPageListInJson.put("startDate",startDate);//开始时间
                medicalRecordPageListInJson.put("endDate",endDate);//结束时间
                //请求接口 2.1.1.	获取门诊信息列表 获取 门诊病历集合
                JSONObject medicalRecordPageListOutJson = getDtHisMedicalRecordPageListOutJson(medicalRecordPageListInJson);//虚拟请求返回参数
                System.out.println(medicalRecordPageListOutJson.toString());
                //判断请求返回标识
                if(medicalRecordPageListOutJson != null){
                    if(medicalRecordPageListOutJson.get("code") != null && "200".equals(medicalRecordPageListOutJson.get("code").toString())){
                        //统计插入数据
                        String tableName = "dt_health_data_outpatient_medical";
                        int dataCount = 0;
                        //获取数据
                        JSONArray recordList = medicalRecordPageListOutJson.getJSONArray("body");
                        for(Object record:recordList){
                            //转换对象
                            DtHisMedicalRecordPageListOutRecordModel medicalRecordPageListOutCardModel = objectMapper
                                    .convertValue(record, DtHisMedicalRecordPageListOutRecordModel.class);
                            //获取门诊病历部分参数作为后续接口入参
                            JSONObject medicalRecordDetailInJson = new JSONObject();
                            medicalRecordDetailInJson.put("organ_code",institutionId);//机构代码
                            medicalRecordDetailInJson.put("sqm",uuid);//权限标识
                            medicalRecordDetailInJson.put("jzlsh",medicalRecordPageListOutCardModel.getJzlsh());//就诊流水号
                            //请求接口 2.1.2.	门诊详情 获取 门诊详情【drugDetails	西药/中成药明细列表】
                            JSONObject medicalRecordDetailOutJson = getDtHisMedicalRecordDetailOutJson(medicalRecordDetailInJson);
                            //判断请求返回标识
                            if(medicalRecordDetailOutJson != null){
                                if(medicalRecordDetailOutJson.get("code") != null && "200".equals(medicalRecordDetailOutJson.get("code").toString())){
                                    try {
                                        //获取数据
                                        DtHisMedicalRecordDetailOutModel medicalRecordDetailOutModel = objectMapper
                                                .convertValue(medicalRecordDetailOutJson.get("body"), DtHisMedicalRecordDetailOutModel.class);
                                        //存储数据到 健康数据 门诊病历
                                        String empiid = saveOutpatientMedicalEntity(medicalRecordPageListOutCardModel,medicalRecordDetailOutModel,uuid);
                                        //成功执行插入累加
                                        dataCount++;
                                        //获取处方集合
                                        List<DtHisMedicalRecordDetailOutDrugModel> drugList = medicalRecordDetailOutModel.getDrugList();
                                        //遍历处方集合
                                        for(DtHisMedicalRecordDetailOutDrugModel drug:drugList){
                                            //存储数据到 门诊病历 成药处方
                                            saveWestPrescriptionEntity(medicalRecordPageListOutCardModel,drug,empiid);
                                        }
                                    }catch (Exception e){
                                        LOGGER.error("存储数据到 健康数据 门诊病历异常！dcid：" + medicalRecordPageListOutCardModel.getDcid());
                                        LOGGER.error(e.getMessage());
                                        //跳过这次循环
                                        continue;
                                    }
                                }else{
                                    //打印错误消息
                                    String msg = medicalRecordPageListOutJson.get("msg").toString();
                                    LOGGER.error("2.1.2 门诊详情 接口返回异常信息！机构代码:" + institutionId + "。异常信息:" + msg);
                                }
                            }
                        }
                        //插入数据量大于0则插入统计数据
                        if(dataCount > 0){
                            saveStatistics(tableName,dataCount);
                        }
                    }else{
                        //打印错误消息
                        String msg = medicalRecordPageListOutJson.get("msg").toString();
                        LOGGER.error("2.1.1 获取门诊信息列表 接口返回异常信息！机构代码:" + institutionId + "。异常信息:" + msg);
                    }
                }
            }
        }
    }

    /**
     * 获取检验/检查数据
     */
    public void task2() {
        //获取结束时间(当前时间)
        Calendar beforeTime = Calendar.getInstance();
        Calendar endTime = Calendar.getInstance();

        //获取开始时间(15分钟前)
        beforeTime.add(Calendar.HOUR, -84);// 24分钟之前的时间
        endTime.add(Calendar.HOUR, -60);
        Date beforeD = beforeTime.getTime();
        Date endD = endTime.getTime();
        String startDate = new SimpleDateFormat("yyyy-MM-dd").format(beforeD) + "T"
                + new SimpleDateFormat("HH:mm:ss").format(beforeD) + "+08:00";
        String endDate = new SimpleDateFormat("yyyy-MM-dd").format(endD) + "T"
                + new SimpleDateFormat("HH:mm:ss").format(endD) + "+08:00";
        task2Function(startDate,endDate);
    }

    public void task2Function(String startDate,String endDate){
        //获取身份标识uuid
        String uuid = getUuid();
        if(uuid != null){
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            //获取全部机构
            List<DtInvsManageInstitutionEntity> institutionList = dtInvsManageInstitutionMapper.selectInvsInstitutionInfoSql(INVS_MANAGE_INSTITUTION_ID);//获取某个地区所有机构
            //遍历机构获取数据
            for(DtInvsManageInstitutionEntity institution:institutionList) {
                String institutionId = institution.getId();
                //门诊详情—检查
                JSONObject medicalRecordExamDetailInJson = new JSONObject();
                medicalRecordExamDetailInJson.put("organ_code",institutionId);//机构编码
                medicalRecordExamDetailInJson.put("sqm",uuid);//权限标识
                medicalRecordExamDetailInJson.put("startDate",startDate);//开始时间
                medicalRecordExamDetailInJson.put("endDate",startDate);//结束时间
                JSONObject medicalRecordExamDetailOutJson = getDtHisMedicalRecordExamDetailOutJson(medicalRecordExamDetailInJson);
                if(medicalRecordExamDetailOutJson != null){
                    if(medicalRecordExamDetailOutJson.get("code") != null && "200".equals(medicalRecordExamDetailOutJson.get("code").toString())){
                        JSONArray recordList = medicalRecordExamDetailOutJson.getJSONArray("body");
                        //统计插入数据
                        String tableName = "dt_invs_exam_report_result";
                        int dataCount = 0;
                        for(Object record:recordList){
                            try {
                                //获取数据
                                DtHisMedicalRecordExamDetailOutModel medicalRecordExamDetailOutModel = objectMapper
                                        .convertValue(record, DtHisMedicalRecordExamDetailOutModel.class);
                                //存储数据到 门诊病历 检查
                                saveDtHisMedicalRecordExamDetailOutModel(medicalRecordExamDetailOutModel,institutionId);
                                //成功执行插入累加
                                dataCount++;
                            }catch (Exception e){
                                LOGGER.error("存储数据到 门诊病历 检查 异常！");
                                LOGGER.error(e.getMessage());
                                //跳过这次循环
                                continue;
                            }
                            //插入数据量大于0则插入统计数据
                            if(dataCount > 0){
                                saveStatistics(tableName,dataCount);
                            }
                        }
                    }else{
                        //打印错误消息
                        String msg = medicalRecordExamDetailOutJson.get("msg").toString();
                        LOGGER.error("2.1.4 门诊详情—检查 接口返回异常信息！机构代码:" + institutionId + "。异常信息:" + msg);
                    }
                }
                //门诊详情—检验
                JSONObject medicalRecordTestDetailInJson = new JSONObject();
                medicalRecordTestDetailInJson.put("organ_code",institutionId);//机构编码
                medicalRecordTestDetailInJson.put("sqm",uuid);//权限标识
                medicalRecordExamDetailInJson.put("startDate",startDate);//开始时间
                medicalRecordExamDetailInJson.put("endDate",startDate);//结束时间
                //请求接口2.1.3.	门诊详情—检验 获取 数据
                JSONObject medicalRecordTestDetailOutJson = getDtHisMedicalRecordTestDetailOutJson(medicalRecordTestDetailInJson);
                //判断请求返回标识
                if(medicalRecordTestDetailOutJson != null){
                    if(medicalRecordTestDetailOutJson.get("code") != null && "200".equals(medicalRecordTestDetailOutJson.get("code").toString())){
                        JSONArray recordList = medicalRecordTestDetailOutJson.getJSONArray("body");
                        for(Object record:recordList){
                            try {
                                //获取数据
                                DtHisMedicalRecordTestDetailOutModel medicalRecordTestDetailOutModel = objectMapper
                                        .convertValue(record, DtHisMedicalRecordTestDetailOutModel.class);
                                //存储数据到 门诊病历 检验
                                saveDtHisMedicalRecordTestDetailOutModel(medicalRecordTestDetailOutModel,institutionId);
                            }catch (Exception e){
                                LOGGER.error("存储数据到 门诊病历 检验 异常！");
                                LOGGER.error(e.getMessage());
                                //跳过这次循环
                                continue;
                            }
                        }
                    }else{
                        //打印错误消息
                        String msg = medicalRecordTestDetailOutJson.get("msg").toString();
                        LOGGER.error("2.1.3 门诊详情—检验 接口返回异常信息！机构代码:" + institutionId + "。异常信息:" + msg);
                    }
                }
            }
        }
    }


    public void task3(){
        //获取结束时间(当前时间)
        Calendar beforeTime = Calendar.getInstance();
        Calendar endTime = Calendar.getInstance();

        //获取开始时间(15分钟前)
        beforeTime.add(Calendar.HOUR, -84);// 24分钟之前的时间
        endTime.add(Calendar.HOUR, -60);
        Date beforeD = beforeTime.getTime();
        Date endD = endTime.getTime();
        String startDate = new SimpleDateFormat("yyyy-MM-dd").format(beforeD) + "T"
                + new SimpleDateFormat("HH:mm:ss").format(beforeD) + "+08:00";
        String endDate = new SimpleDateFormat("yyyy-MM-dd").format(endD) + "T"
                + new SimpleDateFormat("HH:mm:ss").format(endD) + "+08:00";
        task3Function(null,null);
    }

    public void task3Function(String startDate,String endDate){
        //获取身份标识uuid
        String uuid = getUuid();
        if(uuid != null){
            //获取单条药品数据
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            //获取全部机构
            List<DtInvsManageInstitutionEntity> institutionList = dtInvsManageInstitutionMapper .selectInvsInstitutionInfoSql(INVS_MANAGE_INSTITUTION_ID);//获取某个地区所有机构
            //遍历机构获取数据
            for(DtInvsManageInstitutionEntity institution:institutionList){
                String institutionId = institution.getId();
                //1.4药品目录查询
                JSONObject drugListInJson = new JSONObject();
                drugListInJson.put("organ_code",institutionId);//机构编码
                drugListInJson.put("sqm",uuid);//权限标识
                drugListInJson.put("scsj",startDate);//上次请求时间
                //请求1.4药品目录查询接口
                JSONObject drugListOutJson = getDtHisDrugListInJson(drugListInJson);
////                //判断请求返回标识
                if(drugListOutJson != null){
                    if(drugListOutJson.get("success") != null && "true".equals(drugListOutJson.get("success").toString())) {
                        JSONArray drugList = drugListOutJson.getJSONArray("DrugList");
                        //统计插入数据
                        String tableName = "cyhis_base_drug";
                        int dataCount = 0;
                        for(Object drugObj:drugList){
                            try {
                                DtHisDrugOutModel drugOutModel = objectMapper.convertValue(drugObj, DtHisDrugOutModel.class);
                                //存储数据到 药品表
                                saveDtHisDrugOutModel(drugOutModel);
                                //成功执行插入累加
                                dataCount++;
                            }catch (Exception e){
                                LOGGER.error("存储数据到 药品表异常！");
                                LOGGER.error(e.getMessage());
                                //跳过这次循环
                                continue;
                            }
                        }
                        //插入数据量大于0则插入统计数据
                        if(dataCount > 0){
                            saveStatistics(tableName,dataCount);
                        }
                    }else{
                        //打印错误消息
                        String msg = drugListOutJson.get("msg").toString();
                        LOGGER.error("1.4 机构信息获取 接口返回异常信息！机构代码:" + institutionId + "。异常信息:" + msg);
                    }
                }
                //1.6 医生信息获取
                JSONObject doctorListInJson = new JSONObject();
                doctorListInJson.put("organ_code",institutionId);//机构编码
                doctorListInJson.put("sqm",uuid);//权限标识
                doctorListInJson.put("indate",startDate);//上次请求时间
                //请求1.6 医生信息获取接口
                JSONObject dtHisDoctorListOutJson = getDtHisDoctorListOutJson(doctorListInJson);
                //判断请求返回标识
                if(dtHisDoctorListOutJson != null){
                    if(dtHisDoctorListOutJson.get("success") != null && "true".equals(dtHisDoctorListOutJson.get("success").toString())&&dtHisDoctorListOutJson.get("DoctorList") != null) {
                        JSONArray doctorList = dtHisDoctorListOutJson.getJSONArray("DoctorList");
                        //统计插入数据
                        String tableName = "dd_doctor";
                        int dataCount = 0;
                        //循环插入表
                        for(Object doctor:doctorList){
                            try {
                                //获取单条药品数据
                                DtHisDoctorOutModel doctorOutModel = objectMapper.convertValue(doctor, DtHisDoctorOutModel.class);
                                //存储数据到 医生信息
                                saveDtHisDoctorOutModel(doctorOutModel);
                                //成功执行插入累加
                                dataCount++;
                            }catch (Exception e){
                                LOGGER.error("存储数据到 员工表异常！");
                                LOGGER.error(e.getMessage());
                                //跳过这次循环
                                continue;
                            }
                        }
                        //插入数据量大于0则插入统计数据
                        if(dataCount > 0){
                            saveStatistics(tableName,dataCount);
                        }
                    }else{
                        //打印错误消息
                        String msg = dtHisDoctorListOutJson.get("msg").toString();
                        LOGGER.error("1.6 医生信息获取 接口返回异常信息！机构代码:" + institutionId + "。异常信息:" + msg);
                    }
                }
            }
        }
    }

//    public void task4(){
//        ObjectMapper objectMapper = new ObjectMapper();
//        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//        //获取身份标识uuid
//        String uuid = getUuid();
//        if(uuid != null){
//            //1.3 机构信息获取 入参
//            JSONObject getOrganListInJson = new JSONObject();
//            getOrganListInJson.put("sqm",uuid);//权限标识
//            JSONObject getOrganListOutJson = getOrganListJson(getOrganListInJson);
//            //判断请求返回标识
//            if(getOrganListOutJson != null) {
//                if(getOrganListOutJson.get("success") != null && "true".equals(getOrganListOutJson.get("success").toString())) {
//                    //获取数据
//                    JSONArray organList = getOrganListOutJson.getJSONArray("organList");
//                    for(Object organ:organList) {
//                        //转换对象
//                        DtHealthManageInstitutionEntity dtHealthManageInstitutionEntity=new DtHealthManageInstitutionEntity();
//                        DtHisOrganOutModel dtHisOrganOutModel = objectMapper.convertValue(organ, DtHisOrganOutModel.class);
//                        dtHealthManageInstitutionEntity.setId(dtHisOrganOutModel.getOrgan_code());
//                        dtHealthManageInstitutionEntity.setName(dtHisOrganOutModel.getOrgan_name());
//                        //保存数据
//                        dtHealthManageInstitutionMapper.insert(dtHealthManageInstitutionEntity);
//                    }
//                }else{
//                    //打印错误消息
//                    String msg = getOrganListOutJson.get("msg").toString();
//                    LOGGER.error("1.3 机构信息获取 接口返回异常信息！异常信息:" + msg);
//                }
//            }
//        }
//    }

    /**
     * 存储数据到 健康数据 门诊病历
     * @param outCardModel
     */
    public String saveOutpatientMedicalEntity(DtHisMedicalRecordPageListOutRecordModel outCardModel,
                                              DtHisMedicalRecordDetailOutModel detail,String uuid) throws Exception{
        JSONObject healthRecordInJson = new JSONObject();
        healthRecordInJson.put("idcard",outCardModel.getIdCard());//身份证号
        healthRecordInJson.put("sqm",uuid);//权限标识
        //1.5   身份证表身份验证
        JSONObject dtHisHealthRecordOutJson = getDtHisHealthRecordOutJson(healthRecordInJson);
        ///判断请求返回标识
        if(dtHisHealthRecordOutJson != null){
            if(dtHisHealthRecordOutJson.get("success") != null && "true".equals(dtHisHealthRecordOutJson.get("success").toString())){
                //获取数据
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                DtHisPersonaInformationOutModel personaInformationOutModel = objectMapper
                        .convertValue(dtHisHealthRecordOutJson.get("user"), DtHisPersonaInformationOutModel.class);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");//1993-08-09 00:00:00.000+00
                //门诊病历 拼接 (门诊详情、个人档案详情) 存入表dt_health_data_outpatient_medical健康数据 门诊病历
                DtHealthDataOutpatientMedicalEntity entity = new DtHealthDataOutpatientMedicalEntity();
                entity.setInstitutionId(outCardModel.getLocalOrgId());//机构ID,2.1.1医院代码
                entity.setUid(personaInformationOutModel.getEmpiid());//患者身份唯一标识
                entity.setChildId(0);//uid与childId组成 身份唯一标识
                entity.setMedicalSerialNo(outCardModel.getJzlsh());//就诊流水号
                entity.setDoctorId(outCardModel.getLocalDoctorId());//医生id,2.1.1 医生工号
                entity.setName(personaInformationOutModel.getPersonname());//患者姓名
                entity.setGender("".equals(personaInformationOutModel.getSexcode())?0:Integer.parseInt(personaInformationOutModel.getSexcode()));//性别int(2),2.3.1性别代码string
                //根据出生日期计算年龄及月龄
                if(personaInformationOutModel.getBirthday() != null && !"".equals(personaInformationOutModel.getBirthday()) && personaInformationOutModel.getBirthday().length() > 10){
                    Date birthday = format.parse(personaInformationOutModel.getBirthday().substring(0,10));
                    Calendar now = Calendar.getInstance();
                    Calendar b = Calendar.getInstance();
                    b.setTime(birthday);
                    int age = now.get(Calendar.YEAR) - b.get(Calendar.YEAR);
                    int ageMonth = age * 12 + now.get(Calendar.MONTH) - b.get(Calendar.MONTH);
                    entity.setAge(age);//年龄
                    entity.setAgeMonth(ageMonth);//月龄
                }
                entity.setVisitDate(format.parse(detail.getClinicTime()));//就诊日期
                entity.setComplain(outCardModel.getSubjComplaint());//主诉
                entity.setTemperature("".equals(outCardModel.getTemp())?0F:Float.parseFloat(outCardModel.getTemp()));//体温
                entity.setWeight("".equals(personaInformationOutModel.getWeight())?0F:Float.parseFloat(personaInformationOutModel.getWeight()));//体重
                entity.setHeartRate("".equals(personaInformationOutModel.getHeight())?0F:Float.parseFloat(personaInformationOutModel.getHeight()));//身高
                entity.setHeartRate("".equals(outCardModel.getHr())?0F:Float.parseFloat(outCardModel.getHr()));//心率
                entity.setSystolic("".equals(outCardModel.getSbp())?0F:Float.parseFloat(outCardModel.getSbp()));//收缩压
                entity.setDiastolic("".equals(outCardModel.getDbp())?0F:Float.parseFloat(outCardModel.getDbp()));//舒张压
                entity.setDiagnosis(outCardModel.getTitle());//诊断名称
                entity.setAdvice(outCardModel.getCur_Plan());//医嘱
                entity.setAllergy(outCardModel.getAllerhxDescrip());//过敏史
                entity.setSymptom(outCardModel.getPresHx());//现病史
                entity.setGeneticDisease(outCardModel.getGeneticHx());//遗传疾病史
                entity.setPastHistory(outCardModel.getPrevHx());//既往史
                entity.setTz(outCardModel.getTz());//体征
                entity.setInstitutionName(outCardModel.getOrgName());//机构名称
                entity.setId("".equals(outCardModel.getDcid())?"linan0":"linan"+outCardModel.getDcid());//门诊病历ID int(11),2.1.1记录标识string(36)
                //插入到数据库
                dtHealthDataOutpatientMedicalMapper.insertSelective(entity);
                //保存患者数据
                DdRecordBaseInfoEntity ddRecordBaseInfoEntity=new DdRecordBaseInfoEntity();
                if(!CheckUtil.isEmpty(personaInformationOutModel.getEmpiid())){
                    ddRecordBaseInfoEntity.setId(personaInformationOutModel.getEmpiid());
                    ddRecordBaseInfoEntity.setChildId(0);
                    ddRecordBaseInfoEntity.setUid(personaInformationOutModel.getEmpiid());
                    ddRecordBaseInfoEntity.setName(personaInformationOutModel.getPersonname());
                    ddRecordBaseInfoEntity.setInstitutionId(outCardModel.getLocalOrgId());
                    ddRecordBaseInfoEntity.setAge(entity.getAge());
                    ddRecordBaseInfoEntity.setGender(entity.getGender());
                    ddRecordBaseInfoEntity.setAgeMonth(entity.getAgeMonth());
                    ddRecordBaseInfoMapper.insertSelective(ddRecordBaseInfoEntity);
                }
                //获取诊断集合
                List<DtHisMedicalRecordPageListOutRecordDiagnosisModel> diagnosisList = outCardModel.getDiagList();
                if(diagnosisList != null && diagnosisList.size() > 0){
                    //统计插入数据
                    String tableName = "dt_health_data_diagnosis";
                    int dataCount = 0;
                    for(DtHisMedicalRecordPageListOutRecordDiagnosisModel diagnosis:diagnosisList){
                        try {
                            //保存诊断数据
                            saveDtHisMedicalRecordPageListOutRecordDiagnosisModel(diagnosis,outCardModel.getJzlsh(),outCardModel.getLocalOrgId(),personaInformationOutModel.getPersonname());
                            //成功执行插入累加
                            dataCount++;
                        }catch (Exception e){
                            LOGGER.error("存储数据到 诊断表异常！就诊流水号："+diagnosis,outCardModel.getJzlsh());
                            LOGGER.error(e.getMessage());
                            //跳过这次循环
                            continue;
                        }
                    }
                    //插入数据量大于0则插入统计数据
                    if(dataCount > 0){
                        saveStatistics(tableName,dataCount);
                    }
                }
                return personaInformationOutModel.getEmpiid();
            }else{
                //打印错误消息
                String msg = dtHisHealthRecordOutJson.get("msg").toString();
                LOGGER.error("2.1.3 门诊详情—检验 接口返回异常信息！uuid:" + uuid + "。异常信息:" + msg);
                //上抛异常跳过循环
                throw new Exception(msg);
            }
        }else{
            //为空时已打印错误信息，上抛异常无需错误信息
            throw new Exception();
        }
    }


    /**
     * 存储数据到 门诊病历 成药处方
     * @param outCardModel
     * @param drug
     */
    public void saveWestPrescriptionEntity(DtHisMedicalRecordPageListOutRecordModel outCardModel,
                                           DtHisMedicalRecordDetailOutDrugModel drug,String empiid){
        //统计插入数据
        String tableName = "dt_health_data_west_prescription";
        int dataCount = 0;
        //获取明细集合
        List<DtHisMedicalRecordDetailOutDrugDetailModel> drugDetails = drug.getDrugDetails();
        //遍历明细集合
        for(DtHisMedicalRecordDetailOutDrugDetailModel drugDetail:drugDetails){
            try {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                //获取存储处方表数据对象
                DtHealthDataWestPrescriptionEntity entity = new DtHealthDataWestPrescriptionEntity();
                //添加数据
                entity.setId("linan"+drug.getPrescriptionId()+drugDetail.getYpzh());//linan+处方号+处方group唯一确认临安id
                entity.setUid(empiid);//患者身份唯一标识
                entity.setChildId(0);//uid与childId组成 身份唯一标识
                entity.setMedicalId("".equals(outCardModel.getDcid())?"linan0":"linan"+outCardModel.getDcid());//门诊病历ID int(11),2.1.1记录标识string(36)
                entity.setInstitutionId(outCardModel.getLocalOrgId());
                entity.setPrescriptionId(drug.getPrescriptionId());//处方ID int(11),2.1.2处方号string(32)
                entity.setGroupNo("".equals(drugDetail.getYpzh())?0:Integer.parseInt(drugDetail.getYpzh()));//药品组号
                entity.setItemId("".equals(drugDetail.getDrugId())?0:Integer.parseInt(drugDetail.getDrugId()));//item_id int(11),2.1.2药物编码
                entity.setItemName(drugDetail.getDrugName());//药品名称
                entity.setDrugUse(drugDetail.getRoute());//用法code值,用药途径
                entity.setDrugUseText(drugDetail.getCname_Useway_code());//用法code文本
                entity.setSpecification(drugDetail.getSpecifications());//药品规格
                entity.setFrequency(drugDetail.getFrequency());//用药频率
                entity.setFrequencyText(drugDetail.getFrequency());//用药频率文本（打印用）
                entity.setOnceDose("".equals(drugDetail.getSingle_Dose())?0F:Float.parseFloat(drugDetail.getSingle_Dose()));//单次剂量
                entity.setDoseUnit(drugDetail.getDose_Unit());//单次剂量单位
                entity.setDosage("".equals(drugDetail.getTotal_Dose())?0F:Float.parseFloat(drugDetail.getTotal_Dose()));//开药量
                entity.setDosageUnit("");//开药量单位 无对应
                entity.setRetailPrice("".equals(drugDetail.getDrug_P())?0F:Float.parseFloat(drugDetail.getDrug_P()));//零售价 单价
                entity.setIssueDt(format.parse(drugDetail.getRx_Dt()));;//处方开立时间
                entity.setTotalPrice("".equals(drugDetail.getDrug_Amt())?0F:Float.parseFloat(drugDetail.getDrug_Amt()));//总价
                entity.setPrescribingNumber("".equals(drugDetail.getDays())?0:Short.parseShort(drugDetail.getDays()));//用药天数
                entity.setDoctorId(drugDetail.getDoct_Code());//开处方医生编号
                entity.setManufacturer(drugDetail.getFac_Name());//生产厂家
                entity.setDoctorName(drugDetail.getDoct_Name());//医生名称
                LOGGER.info("就诊流水号为："+outCardModel.getDcid());
                //插入到数据库
                dtHealthDataWestPrescriptionMapper.insertSelective(entity);
                //成功执行插入累加
                dataCount++;
            }catch (Exception e){
                LOGGER.error("存储数据到 成药处方异常！记录标识："+outCardModel.getDcid());
                LOGGER.error(e.getMessage());
                //跳过这次循环
                continue;
            }
        }
        //插入数据量大于0则插入统计数据
        if(dataCount > 0){
            saveStatistics(tableName,dataCount);
        }
    }

    /**
     * 存储数据到 门诊病历 检验
     * @param outModel
     */
    public void saveDtHisMedicalRecordTestDetailOutModel(DtHisMedicalRecordTestDetailOutModel outModel,
                                                         String institutionId){
        //统计插入数据
        String tableName = "dt_health_data_medical_test";
        int dataCount = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        for(DtHisMedicalRecordTestDetailOutResultModel result:outModel.getResultList()){
            DtHealthDataMedicalTest entity = new DtHealthDataMedicalTest();
            entity.setMedicalId(outModel.getMzh());//门诊号,mzh	流水号(门诊号)
            entity.setInstitutionId(institutionId);//机构编号
            //entity.setMedicalId(0);//'门诊病历ID'
            //entity.setPrescriptionId(0);//'处方ID'
            entity.setItemId(result.getItemCode());//itemId ,itemCode 项目代码
            entity.setItemName(result.getItemName());//检查治疗项目,项目名称
            entity.setSpecimenText(result.getSampleType());//标本
            entity.setComment(result.getRemark());//备注
            //dtHealthDataMedicalTest.setDoctorId(Integer.parseInt(medicalRecordTestDetailOutModel.getDoctor()));//开处方医生,doctor送检医生
            entity.setCheckDoctor(outModel.getDoctor());//送检医生
            try {
                entity.setIssueDt(format.parse(result.getReportorTime()));//出具日期，报告时间
            }catch (Exception e){}
            dtHealthDataMedicalTestMapper.insertSelective(entity);
            //成功执行插入累加
            dataCount++;
        }
        //插入数据量大于0则插入统计数据
        if(dataCount > 0){
            saveStatistics(tableName,dataCount);
        }
    }

    /**
     * 存储数据到 门诊病历 检查
     * @param outModel
     */
    public void saveDtHisMedicalRecordExamDetailOutModel(DtHisMedicalRecordExamDetailOutModel outModel,
                                                         String institutionId){
        DtInvsExamReportResultEntity entity = new DtInvsExamReportResultEntity();
        entity.setMedicalSerialNo(outModel.getOp_em_hp_ex_no());//就诊流水号
        //entity.setPersonalNo("");//病历编号
        entity.setInstitutionId(institutionId);//医疗机构编码
        //entity.setPrescriptionId("");//处方编码
        //entity.setExamPara("");//检查参数
        entity.setExamObjectiveDesc(outModel.getNormalname());//检查项目名称,报告单名称
        entity.setExamDesc(outModel.getImpression());//检查报告描述
        entity.setRecommendation(outModel.getDescription());//说明
        //entity.setExamAim("");//检查目的 无对应
        //entity.setResult("");//检查结果(0:正常  1：不正常)
        entity.setDoctorId("".equals(outModel.getChk_doc_code())?0:Integer.parseInt(outModel.getChk_doc_code()));//开立医生
        entity.setOperateTm(outModel.getDate_of_birth());//操作时间,检验时间
        entity.setXmlNote(outModel.getXmlNote());//图片地址
        entity.setLastsavetime(outModel.getLastsavetime());//上次检查时间
        entity.setName(outModel.getName());//姓名
        entity.setSexcode(outModel.getSexCode());//患者性别（代码）
        entity.setIdCard(outModel.getIdcard());//身份证号
        dtInvsExamReportResultMapper.insertSelective(entity);
    }

    /**
     * 存储数据到 药品表
     * @param drugOutModel
     */
    public void saveDtHisDrugOutModel(DtHisDrugOutModel drugOutModel){
        CyhisBaseDrugEntity entity = new CyhisBaseDrugEntity();
        entity.setInstitutionId(drugOutModel.getOrgan_code());//机构编码
        //entity.setBaseItemId();//药品基础表主键id
        entity.setId(drugOutModel.getYyzbdm());//药品id
        entity.setDrugId(drugOutModel.getYyzbdm());//药品id
        entity.setRegisterCode(drugOutModel.getYppzwh());//批准文号：国药准字|注册证号
        entity.setName(drugOutModel.getYwmc());//药品名称(his传过来的药品名称)
        entity.setDrugName(drugOutModel.getTymc());//药品通用名
        entity.setSpecification(drugOutModel.getYpgg());//规格
        entity.setPrepForm(drugOutModel.getJxmc());//剂型,剂型名称
        entity.setManufacturer(drugOutModel.getCdmc());//药品生产厂家，产地名称
        entity.setManufacturerCode(drugOutModel.getCddm());//产地编码
        //entity.setDrugCode();//药品编码(医保)
        //entity.setDrugType(Short.parseShort(drugOutModel.getTbsm()));//药品类型(11:西药 12:中成药)
        entity.setDrugTypeTxt(drugOutModel.getTbsm());//药品类型文字
        //entity.setBarCode();//药品条码
        //entity.setContentSpec();//含量规格
        //entity.setContentSpecUnit();//含量规格单位
        entity.setContentUnitText(drugOutModel.getYpdw());//含量规格单位文本
        //entity.setPreparationAmount();//制剂数量
        //entity.setPreparationUnit();//制剂单位
        //entity.setPreparationUnitText();//制剂单位文本
        //entity.setStockKeepingUnit();//库存单位
        //entity.setStockKeepingUnitText();//库存单位文本
        cyhisBaseDrugMapper.insertSelective(entity);
    }

    /**
     * 存储数据到 医生信息表
     * @param doctorOutModel
     */
    public void saveDtHisDoctorOutModel(DtHisDoctorOutModel doctorOutModel){
        DdDoctorEntity entity = new DdDoctorEntity();
        entity.setQyUserId(doctorOutModel.getPersonid());//企业号用户id
        entity.setId(doctorOutModel.getPersoncode());
        entity.setDoctorId(doctorOutModel.getPersoncode());
        entity.setName(doctorOutModel.getPersonname());//医生姓名
        entity.setHeadImgUrl(doctorOutModel.getImg());//医生头像URL
        entity.setInstitutionId(doctorOutModel.getOrgan_code());//医疗机构编码
        entity.setInstitutionName(doctorOutModel.getOrgan_name());//医疗机构名称
        entity.setPhone(doctorOutModel.getMobile());//电话
        //entity.setDepartment(doctorOutModel.getJobpost());//所属科室
        entity.setComment(doctorOutModel.getRemark());//备注说明
        entity.setIdCard(doctorOutModel.getCardnum());//身份证号
        entity.setQualification(doctorOutModel.getMajorqualify());//医生资格证书号

        //先判断是否存在，存在就更新
        DdDoctorEntity ddDoctorEntitySearch=new DdDoctorEntity();
        ddDoctorEntitySearch.setId(doctorOutModel.getPersoncode());
        ddDoctorEntitySearch.setInstitutionId(doctorOutModel.getOrgan_code());
        DdDoctorEntity ddDoctorEntityResult=ddDoctorMapper.selectDoctorInfoByIdAndInstitution(doctorOutModel.getPersoncode(),doctorOutModel.getOrgan_code());
        if(!CheckUtil.isEmpty(ddDoctorEntityResult)){
            if(!CheckUtil.isEmpty(doctorOutModel.getCardnum())){
                ddDoctorMapper.updateById(doctorOutModel.getPersoncode(),doctorOutModel.getOrgan_code(),doctorOutModel.getCardnum());
            }
        }else{
            ddDoctorMapper.insertSelective(entity);
            //医生跟医疗机构关系数据存储到dt_health_manage_institution_doctor
            saveDtHisInstitutionDoctorOutModel(doctorOutModel);
        }
    }

    /**
     * 存储数据到 医疗机构对应医生关系信息表
     * @param doctorOutModel
     */
    public void saveDtHisInstitutionDoctorOutModel(DtHisDoctorOutModel doctorOutModel){
        DtHealthManageInstitutionDoctorEntity entity = new DtHealthManageInstitutionDoctorEntity();
        DtHealthManageInstitutionEntity dtHealthManageInstitutionEntity=new DtHealthManageInstitutionEntity();
        dtHealthManageInstitutionEntity.setId(doctorOutModel.getOrgan_code());
        entity.setInstitution(dtHealthManageInstitutionEntity);
        entity.setName(doctorOutModel.getPersonname());//医生姓名
        entity.setId(doctorOutModel.getPersoncode());
        entity.setLoginUser(doctorOutModel.getPersoncode());
        dtHealthManageInstitutionDoctorMapper.insertForInvs(entity);
    }

    /**
     * 存储数据到 诊断表
     * @param diagnosis
     */
    public void saveDtHisMedicalRecordPageListOutRecordDiagnosisModel(DtHisMedicalRecordPageListOutRecordDiagnosisModel diagnosis,
                                                                      String jzlsh,String institutionId,String name){
        DtHealthDataDiagnosisEntity entity = new DtHealthDataDiagnosisEntity();
        entity.setMedicalSerialNo(jzlsh);//就诊流水号
        entity.setInstitutionId(institutionId);//医疗机构代码
        entity.setName(name);//患者姓名
        entity.setDiagnosisCode(diagnosis.getJbzdbm());//诊断编码,诊断代码
        entity.setDiagnosisName(diagnosis.getJbzmmc());//诊断名称
        entity.setDiagnosisType(diagnosis.getZxyzdbs());//诊断类型，中医/西医诊断标志（1中医；2西医）
        entity.setDiagnosisSign(diagnosis.getZczdbs());//主从诊断标识（1主诊断；2从诊断）
        dtHealthDataDiagnosisEntityMapper.insertSelective(entity);
    }

    /**
     * 保存 插入数据统计
     */
    public void saveStatistics(String tableName,int dataCount){
        MaInvsDataExchangeStatisticsEntity exchangeStatistics = new MaInvsDataExchangeStatisticsEntity();
        exchangeStatistics.setTableName(tableName);
        exchangeStatistics.setType(3);//类型 1插入失败 2更新失败 3创业数据获取
        exchangeStatistics.setDataCount(dataCount);
        exchangeStatisticsMapper.insertSelective(exchangeStatistics);
    }


    public String getUuid(){//DtInvsManageInstitutionEntity institution
        try {
            //1.2 机构权限申请
            JSONObject organVerifyInJson = new JSONObject();
            organVerifyInJson.put("ipip",INVS_IP);//ip地址
            organVerifyInJson.put("yhm",INVS_NAME);//用户名
//            organVerifyInJson.put("ipip",institution.getInstitutionIp());//ip地址
//            organVerifyInJson.put("yhm",institution.getName());//用户名
            //请求接口获取机构权限uuid
            JSONObject organVerifyOutJson = getOrganVerifyOutJson(organVerifyInJson);
            //判断请求返回标识
            if(organVerifyOutJson != null){
                if(organVerifyOutJson.get("success") != null && "true".equals(organVerifyOutJson.get("success").toString())) {
                    return  organVerifyOutJson.get("msg").toString();
                }else{
                    //打印错误消息
                    String msg = organVerifyOutJson.get("msg").toString();
                    LOGGER.error("1.2 机构权限申请 接口返回异常信息！异常信息:" + msg);
                }
            }
        }catch (Exception e){
            LOGGER.error("getUuid异常："+e.getMessage());
        }
        return null;
    }


    /**
     * 请求返回参数 1.2机构权限申请
     * @param json
     * @return JSONObject
     */
    public JSONObject getOrganVerifyOutJson(JSONObject json){
        try {
            String url = REQUEST_IP + "/organVerify";
            return HttpClientUtil.sendPost(json , url);
        }catch (Exception e){
            LOGGER.error("1.2 机构权限申请 接口请求异常：" + e.getMessage());
            return null;
        }
    }

    /**
     * 请求返回参数 1.4 药品目录查询
     * @param json
     * @return JSONObject
     */
    public JSONObject getDtHisDrugListInJson(JSONObject json){
        try {
            String url = REQUEST_IP + "/drugLoad";
            return HttpClientUtil.sendPost(json , url);
        }catch (Exception e){
            LOGGER.error("1.4 药品目录查询 接口请求异常：" + e.getMessage());
            return null;
        }
    }

    /**
     * 请求返回参数 1.5   身份证表身份验证
     * @param json
     * @return JSONObject
     */
    public JSONObject getDtHisHealthRecordOutJson(JSONObject json){
        try {
            String url = REQUEST_IP + "/getHzxx";
            return HttpClientUtil.sendPost(json , url);
        }catch (Exception e){
            LOGGER.error("1.5 身份证表身份验证 接口请求异常：" + e.getMessage());
            return null;
        }
    }

    /**
     * 请求返回参数 1.6  医生信息获取
     * @param json
     * @return JSONObject
     */
    public JSONObject getDtHisDoctorListOutJson(JSONObject json){
        try {
            String url = REQUEST_IP + "/doctorLoad";
            return HttpClientUtil.sendPost(json , url);
        }catch (Exception e){
            LOGGER.error("1.6  医生信息获取 接口请求异常：" + e.getMessage());
            return null;
        }
    }

    /**
     * 请求返回参数 2.1.1.	获取门诊信息列表
     * @param json
     * @return JSONObject
     */
    public JSONObject getDtHisMedicalRecordPageListOutJson(JSONObject json){
        try {
            String url = REQUEST_IP + "/medicalRecordList";
            return HttpClientUtil.sendPost(json , url);
        }catch (Exception e){
            LOGGER.error("2.1.1. 获取门诊信息列表 接口请求异常：" + e.getMessage());
            return null;
        }
    }

    /**
     * 请求返回参数 2.1.2.	门诊详情
     * @param json
     * @return JSONObject
     */
    public JSONObject getDtHisMedicalRecordDetailOutJson(JSONObject json){
        try {
            String url = REQUEST_IP + "/medicalRecordDetail";
            return HttpClientUtil.sendPost(json , url);
        }catch (Exception e){
            LOGGER.error("2.1.2. 门诊详情 接口请求异常：" + e.getMessage());
            return null;
        }
    }

    /**
     * 请求返回参数 2.1.3.	门诊详情—检验
     * @param json
     * @return JSONObject
     */
    public JSONObject getDtHisMedicalRecordTestDetailOutJson(JSONObject json){
        try {
            String url = REQUEST_IP + "/medicalRecordTest";
            return HttpClientUtil.sendPost(json , url);
        }catch (Exception e){
            LOGGER.error("2.1.3. 门诊详情—检验 接口请求异常：" + e.getMessage());
            return null;
        }
    }

    /**
     * 请求返回参数 2.1.4.	门诊详情—检查
     * @param json
     * @return DtHisMedicalRecordExamDetailOutModel
     */
    public JSONObject getDtHisMedicalRecordExamDetailOutJson(JSONObject json){
        try {
            String url = REQUEST_IP + "/medicalRecordExam";
            return HttpClientUtil.sendPost(json , url);
        }catch (Exception e){
            LOGGER.error("2.1.4. 门诊详情—检查 接口请求异常：" + e.getMessage());
            return null;
        }
    }

    /**
     * 获取医疗机构
     * @param json
     * @return
     */
    public JSONObject getOrganListJson(JSONObject json){
        try {
            String url = REQUEST_IP + "/organList";
            return HttpClientUtil.sendPost(json , url);
        }catch (Exception e){
            LOGGER.error("1.3 机构信息获取 接口请求异常：" + e.getMessage());
            return null;
        }
    }


    @Resource
    private DataFromInvsWebService dataFromInvsWebService;
    @Resource
    private AllTypesTableMapper allTypesTableMapper;
    @Resource
    private DtInvsManageInstitutionMapper dtInvsManageInstitutionMapper;
    @Resource
    private SpecialTransmissionDataMapper specialTransmissionDataMapper;
    @Resource
    private MaInvsDataExchangeParameterColumnMapper parameterColumnMapper;
    @Resource
    private MaInvsDataExchangeSpecialTableMapper specialTransmissionTableMapper;
    @Resource
    private MaInvsDataExchangeErrorMapper exchangeErrorMapper;
    @Resource
    private ParameterTableMapper parameterTableMapper;


    /**
     * 定时获取数据保存到新表
     */
    public void taskTest() {
        String accessUrl = "";
        if (EnvironmentProperties.getEnvType() == EnvironmentEnum.DEV) {
            accessUrl = "http://localhost:8060/invs_linan/exchange_his_data.do/save";//InvsDataExchangeProperties.LINAN_DATA_EXCHANGE_TEST_URL;
        } else {
            accessUrl = "http://192.168.3.87:8060/invs/exchange_his_data.do/save";//InvsDataExchangeProperties.LINAN_DATA_EXCHANGE_URL;
        }
        System.out.println("-------------------------------START--------------------------------------");
        //需要处理的表
        List<String> tableNames = parameterTableMapper.selectInsertTable();
        //需要进行特殊查询的表
        Map<String, MaInvsDataExchangeSpecialTableEntity> specialTables = getSpecialTables();
        //需要进行特殊字段处理的表及字段
        Map<String, List<MaInvsDataExchangeSpecialDataEntity>> specialDatas = getSpecialDatas();
        //查询的表字段
        Map<String, List<String>> parameterColumns = getSelectInsertColumns();
        //获取临安机构ID集合
        List<Object> institutionIds = dtInvsManageInstitutionMapper.selectInvsInstitutionSql("00000001");
        if(institutionIds != null && institutionIds.size() > 0){
            for(String tableName:tableNames){
                //获取需要发送的数据
                List<Map<String, Object>> dataList = getDataByTableName(tableName ,institutionIds, specialTables, parameterColumns);
                //存在需要传输的数据才继续执行
                if(dataList != null && dataList.size() > 0){
                    //特殊字段处理(图片url转base64等)
                    dataList = specialColumn(tableName,dataList,specialDatas,accessUrl);
                    //处理时间格式数据
                    dataList = timeFormat(dataList);
                    //请求接口
                    JSONObject resultJson = HttpClientUtil.sendPost2(tableName, dataList, accessUrl);
                    //获取接口返回参数判断状态
                    if(resultJson != null && resultJson.get("errcode") != null && "0".equals(resultJson.get("errcode"))){
                        //获取成功数据，修改状态
                        if(resultJson.get("completeIds") != null && resultJson.get("completeIds") instanceof List<?>){
                            List<Object> completeIds = (List<Object>)resultJson.get("completeIds");
                            if(completeIds.size() > 0){
                                //修改发送成功数据
                                updateSendCompleteData(tableName,completeIds);
                            }
                        }
                        //获取失败数据，修改状态
                        if(resultJson.get("errorIds") != null && resultJson.get("errorIds") instanceof List<?>){
                            List<Object> errorIds = (List<Object>)resultJson.get("errorIds");
                            if(errorIds.size() > 0){
                                //修改发送失败数据
                                updateSendErrorData(tableName,errorIds);
                            }
                        }
                    }else{
                        LOGGER.error("定时获取数据保存到新表：接口请求失败！");
                    }
                }
            }
        }else {
            LOGGER.error("定时获取数据保存到新表：institutionIds集合为空或长度为0！跳过本次任务！");
        }
        System.out.println("--------------------------------END---------------------------------------");
    }


    /**
     * 定时获取数据更新到新库
     */
    public void taskTest2() {
        String accessUrl = "";
        if (EnvironmentProperties.getEnvType() == EnvironmentEnum.DEV) {
            accessUrl = "http://localhost:8060/invs_linan/exchange_his_data.do/update";//InvsDataExchangeProperties.LINAN_DATA_EXCHANGE_TEST_URL;
        } else {
            accessUrl = "http://192.168.3.87:8060/invs/exchange_his_data.do/update";//InvsDataExchangeProperties.LINAN_DATA_EXCHANGE_URL;
        }
        System.out.println("-------------------------------传输数据更新START--------------------------------------");
        //需要处理的表
        List<String> tableNames = parameterTableMapper.selectUpdateTable();
        //需要进行特殊查询的表
        Map<String, MaInvsDataExchangeSpecialTableEntity> specialTables = getSpecialTables();
        //需要进行特殊字段处理的表及字段
        //Map<String, List<MaInvsDataExchangeSpecialDataEntity>> specialDatas = getSpecialDatas();
        //查询的表字段
        Map<String, List<String>> parameterColumns = getSelectUpdateColumns();
        //获取临安机构ID集合
        List<Object> institutionIds = dtInvsManageInstitutionMapper.selectInvsInstitutionSql("00000001");
        if(institutionIds != null && institutionIds.size() > 0){
            for(String tableName:tableNames){
                //获取需要发送的数据
                List<Map<String, Object>> dataList = getUpdateDataByTableName(tableName ,institutionIds, specialTables, parameterColumns);
                //存在需要传输的数据才继续执行
                if(dataList != null && dataList.size() > 0){
                    //特殊字段处理(图片url转base64等)
                    //dataList = specialColumn(tableName,dataList,specialDatas,accessUrl);
                    //处理时间格式数据
                    dataList = timeFormat(dataList);
                    //请求接口
                    JSONObject resultJson = HttpClientUtil.sendPost2(tableName, dataList, accessUrl);
                    //获取接口返回参数判断状态
                    if(resultJson != null && resultJson.get("errcode") != null && "0".equals(resultJson.get("errcode"))){
                        //获取成功数据，修改状态
                        if(resultJson.get("completeIds") != null && resultJson.get("completeIds") instanceof List<?>){
                            List<Object> completeIds = (List<Object>)resultJson.get("completeIds");
                            if(completeIds.size() > 0){
                                //修改发送成功数据
                                updateSendCompleteData(tableName,completeIds);
                            }
                        }
                        //获取失败数据，修改状态
                        if(resultJson.get("errorIds") != null && resultJson.get("errorIds") instanceof List<?>){
                            List<Object> errorIds = (List<Object>)resultJson.get("errorIds");
                            if(errorIds.size() > 0){
                                //修改发送失败数据
                                updateSendErrorDataIsUpdate(tableName,errorIds);
                            }
                        }
                    }else{
                        LOGGER.error("定时获取数据保存到新表：接口请求失败！");
                    }
                }
            }
        }else {
            LOGGER.error("定时获取数据更新到新库：institutionIds集合为空或长度为0！跳过本次任务！");
        }
        System.out.println("--------------------------------传输数据更新END---------------------------------------");
    }

    /**
     * 定时获取内网更新数据
     */
    public void taskTest3() {
        String accessUrl = "";
        if (EnvironmentProperties.getEnvType() == EnvironmentEnum.DEV) {
            accessUrl = "http://localhost:8060/invs_linan/exchange_his_data.do/getUpdateDate";//InvsDataExchangeProperties.LINAN_DATA_EXCHANGE_TEST_URL;
        } else {
            accessUrl = "http://localhost:18080/invs_linan/exchange_his_data.do/getUpdateDate";//InvsDataExchangeProperties.LINAN_DATA_EXCHANGE_URL;
        }
        System.out.println("-------------------------------获取内网更新数据START--------------------------------------");
        //需要处理的表
        List<String> tableNames = parameterTableMapper.selectGetUpdateTable();
        for(String tableName:tableNames){
            List<Map<String, Object>> dataList = new ArrayList<>();
            JSONObject resultJson = HttpClientUtil.sendPost2(tableName, dataList, accessUrl);
            //获取接口返回参数判断状态
            if(resultJson != null && resultJson.get("errcode") != null && "0".equals(resultJson.get("errcode"))){
                //获取数据成功，更新数据
                if(resultJson.get("updateList") != null && resultJson.get("updateList") instanceof List<?>){
                    List<Object> updateList = (List<Object>)resultJson.get("updateList");
                    if(updateList.size() > 0){
                        for(Object dataObj:updateList){
                            if(dataObj instanceof Map<?,?>){
                                Map<String,Object> data = (Map<String,Object>)dataObj;
                                AllTypesTableEntity entity = new AllTypesTableEntity();
                                //获取主键
                                Object id = data.get("id");
                                try {
                                    entity.setWhereStr("id = " + id);
                                    entity.setTableName(tableName);
                                    //剔除主键及特殊键
                                    data.remove("id");
                                    data.remove("obtain_tm");
                                    entity.setParams(data);
                                    allTypesTableMapper.updateReplace(entity);
                                }catch (Exception e){
                                    LOGGER.error(tableName + "表更新内网数据失败，主键：" + id);
                                }
                            }
                        }
                    }
                }
            }else{
                LOGGER.error("定时获取内网更新数据同步到外网：接口请求失败！");
            }
        }
        System.out.println("--------------------------------获取内网更新数据END---------------------------------------");
    }

    /**
     * 获取需要的表数据
     */
    public List<Map<String,Object>> getDataByTableName(String tableName,List<Object> completeIds, Map<String, MaInvsDataExchangeSpecialTableEntity> specialTables,
                                                       Map<String, List<String>> parameterColumns){
        try {
            //查询字段
            List<String> columns = parameterColumns.get(tableName);
            if(columns == null || columns.size() == 0){
                columns = new ArrayList<>();
                columns.add("*");//未设置则默认查询全部
            }
            //查询条件
            AllTypesTableEntity entity = new AllTypesTableEntity();
            entity.setTableName(tableName);
            entity.setIds(completeIds);
            entity.setColumns(columns);
            //特殊结构表需要做特殊处理(无institutionId机构ID字段表)
            if("特殊结构表".equals(tableName)){
                return null;
            }else if("dt_health_manage_institution".equals(tableName)){
                //id字段为institutionId
                return allTypesTableMapper.selectInIds(entity);
            }else if("dt_health_manage_institution_group".equals(tableName)){
                //id字段为parent_institution_id
                return allTypesTableMapper.selectInParentInstitutionIds(entity);
            }else{
                //如果是特殊查询表
                MaInvsDataExchangeSpecialTableEntity tableEntity = specialTables.get(tableName);
                if(tableEntity != null){
                    //特殊表关联查询
                    entity.setJoinStr(tableEntity.getJoinstr());
                    entity.setWhereStr(tableEntity.getWherestr());
                    return allTypesTableMapper.selectInInstitutionIdsOfJoin(entity);
                }else{
                    //默认查询
                    return allTypesTableMapper.selectInInstitutionIds(entity);
                }
            }
        }catch (Exception e){
            String errorMsg = tableName + "表查询失败！" + e.getMessage();
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            saveErrorMsg(tableName,errorMsg,sw.toString());
        }
        return null;
    }

    /**
     * 获取需要的更新表数据
     */
    public List<Map<String,Object>> getUpdateDataByTableName(String tableName,List<Object> completeIds, Map<String, MaInvsDataExchangeSpecialTableEntity> specialTables,
                                                             Map<String, List<String>> parameterColumns){
        try {
            //查询字段
            List<String> columns = parameterColumns.get(tableName);
            if(columns == null || columns.size() == 0){
                columns = new ArrayList<>();
                columns.add("*");//未设置则默认查询全部
            }
            //查询条件
            AllTypesTableEntity entity = new AllTypesTableEntity();
            entity.setTableName(tableName);
            entity.setIds(completeIds);
            entity.setColumns(columns);
            //特殊结构表需要做特殊处理(无institutionId机构ID字段表)
            if("特殊结构表".equals(tableName)){
                return null;
            }else if("dt_health_manage_institution".equals(tableName)){
                //id字段为institutionId
                return allTypesTableMapper.selectUpdateInIds(entity);
            }else if("dt_health_manage_institution_group".equals(tableName)){
                //id字段为parent_institution_id
                return allTypesTableMapper.selectUpdateInParentInstitutionId(entity);
            } else{
                //如果是特殊查询表
                MaInvsDataExchangeSpecialTableEntity tableEntity = specialTables.get(tableName);
                if(tableEntity != null){
                    //特殊表关联查询
                    entity.setJoinStr(tableEntity.getJoinstr());
                    entity.setWhereStr(tableEntity.getWherestr());
                    return allTypesTableMapper.selectUpdateInInstitutionIdsOfJoin(entity);
                }else{
                    //默认查询
                    return allTypesTableMapper.selectUpdateInInstitutionIds(entity);
                }
            }
        }catch (Exception e){
            String errorMsg = tableName + "表更新查询失败！" + e.getMessage();
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            saveErrorMsg(tableName,errorMsg,sw.toString());
        }
        return null;
    }

    //需要特殊更新表的集合
    String[] SPECIAL_TABLE = {"dt_health_manage_institution_doctor","dt_clinic_trade_prescription","dt_clinic_trade_prescription_item","dt_invs_instrument_disinfect_detail","dt_invs_waste_delivery_detail","dd_doctor"};

    /**
     * 发送成功修改数据
     */
    public void updateSendCompleteData(String tableName,List<Object> ids){
        try {
            //特殊结构表需要做特殊处理(无institutionId机构ID字段表)
            if("特殊结构表".equals(tableName)){

            }else if(Arrays.asList(SPECIAL_TABLE).contains(tableName)){
                //多个主键 执行更新
                for(Object id:ids){
                    try {
                        //获取更新主键
                        AllTypesTableEntity entity = new AllTypesTableEntity();
                        entity.setTableName(tableName);
                        entity.setParams(getUpdateParams(id));
                        allTypesTableMapper.updateSendCompleteDataByKeys(entity);
                    }catch (Exception e){
                        String errorMsg = tableName + "表更新失败！" + e.getMessage();
                        StringWriter sw = new StringWriter();
                        e.printStackTrace(new PrintWriter(sw, true));
                        saveErrorMsg(tableName,errorMsg,sw.toString());
                    }
                }
            }else{
                AllTypesTableEntity entity = new AllTypesTableEntity();
                entity.setTableName(tableName);
                entity.setIds(ids);
                allTypesTableMapper.updateSendCompleteData(entity);
            }
        }catch (Exception e){
            String errorMsg = tableName + "表更新失败！" + e.getMessage();
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            saveErrorMsg(tableName,errorMsg,sw.toString());
        }
    }

    /**
     * 发送失败修改数据
     */
    public void updateSendErrorData(String tableName,List<Object> ids){
        try{
            //特殊结构表需要做特殊处理(无institutionId机构ID字段表)
            if("特殊结构表".equals(tableName)){

            }else if(Arrays.asList(SPECIAL_TABLE).contains(tableName)){
                //多个主键 执行更新
                for(Object id:ids){
                    try {
                        //获取更新主键
                        AllTypesTableEntity entity = new AllTypesTableEntity();
                        entity.setTableName(tableName);
                        entity.setParams(getUpdateParams(id));
                        allTypesTableMapper.updateSendErrorDataByKeys(entity);
                    }catch (Exception e){
                        String errorMsg = tableName + "表更新失败！" + e.getMessage();
                        StringWriter sw = new StringWriter();
                        e.printStackTrace(new PrintWriter(sw, true));
                        saveErrorMsg(tableName,errorMsg,sw.toString());
                    }
                }
            }else{
                AllTypesTableEntity entity = new AllTypesTableEntity();
                entity.setTableName(tableName);
                entity.setIds(ids);
                allTypesTableMapper.updateSendErrorData(entity);
            }
        }catch (Exception e){
            String errorMsg = tableName + "表更新失败！" + e.getMessage();
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            saveErrorMsg(tableName,errorMsg,sw.toString());
        }
    }

    /**
     * 发送失败修改数据
     */
    public void updateSendErrorDataIsUpdate(String tableName,List<Object> ids){
        try{
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //特殊结构表需要做特殊处理(无institutionId机构ID字段表)
            if("特殊结构表".equals(tableName)){

            }else if(Arrays.asList(SPECIAL_TABLE).contains(tableName)){
                //多个主键 执行更新
                for(Object id:ids){
                    try {
                        //获取更新主键
                        AllTypesTableEntity entity = new AllTypesTableEntity();
                        entity.setTableName(tableName);
                        entity.setParams(getUpdateParams(id));
                        //更新时间为当前时间前一秒避免下次无法获取到
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(new Date());
                        calendar.add(Calendar.DAY_OF_MONTH, -1);
                        entity.setSendTime(format.format(calendar.getTime()));
                        allTypesTableMapper.updateSendErrorDataIsUpdateByKeys(entity);
                    }catch (Exception e){
                        String errorMsg = tableName + "表更新失败！" + e.getMessage();
                        StringWriter sw = new StringWriter();
                        e.printStackTrace(new PrintWriter(sw, true));
                        saveErrorMsg(tableName,errorMsg,sw.toString());
                    }
                }
            }else{
                AllTypesTableEntity entity = new AllTypesTableEntity();
                entity.setTableName(tableName);
                entity.setIds(ids);
                allTypesTableMapper.updateSendErrorDataIsUpdate(entity);
            }
        }catch (Exception e){
            String errorMsg = tableName + "表更新失败！" + e.getMessage();
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            saveErrorMsg(tableName,errorMsg,sw.toString());
        }
    }

    public Map<String,Object> getUpdateParams(Object id){
        //获取更新主键
        String[] updateCols = ("" + id).split(";");//英文封号【;】
        Map<String,Object> params = new HashMap<>();
        for (String updateCol:updateCols){
            String[] split = updateCol.split(":");//英文冒号【:】
            if(split.length == 2){
                params.put(split[0],split[1]);
            }
        }
        return params;
    }

    /**
     * 获取需要特殊查询的表
     * @return
     */
    public Map<String, MaInvsDataExchangeSpecialTableEntity> getSpecialTables(){
        Map<String, MaInvsDataExchangeSpecialTableEntity> returnMap = new HashMap<>();
        //返回数据
        List<MaInvsDataExchangeSpecialTableEntity> specialTables = specialTransmissionTableMapper.selectAllData();
        //对返回数据进行数据格式处理，方便后续循环判断
        for(MaInvsDataExchangeSpecialTableEntity specialTable:specialTables){
            returnMap.put(specialTable.getTable(),specialTable);
        }
        return returnMap;
    }


    /**
     * 获取需要特殊处理的表和字段及处理方式
     * @return
     */
    public Map<String, List<MaInvsDataExchangeSpecialDataEntity>> getSpecialDatas(){
        Map<String, List<MaInvsDataExchangeSpecialDataEntity>> returnMap = new HashMap<>();
        //返回数据
        List<MaInvsDataExchangeSpecialDataEntity> specialDataList = specialTransmissionDataMapper.selectAllData();
        //对返回数据进行数据格式处理，方便后续循环判断
        for(MaInvsDataExchangeSpecialDataEntity specialData:specialDataList){
            List<MaInvsDataExchangeSpecialDataEntity> specialDataByTable = returnMap.get(specialData.getTable());
            if(specialDataByTable == null){
                specialDataByTable = new ArrayList<>();
            }
            specialDataByTable.add(specialData);
            returnMap.put(specialData.getTable(),specialDataByTable);
        }
        return returnMap;
    }

    /**
     * 获取全部表需要传输的字段
     * @return
     */
    public Map<String, List<String>> getSelectInsertColumns(){
        Map<String, List<String>> returnMap = new HashMap<>();
        //返回数据
        List<MaInvsDataExchangeParameterColumnEntity> parameterColumnList = parameterColumnMapper.selectInsertColumn();
        //对返回数据进行数据格式处理，方便后续循环判断
        for(MaInvsDataExchangeParameterColumnEntity parameterColumn:parameterColumnList){
            List<String> parameterColumnByTable = returnMap.get(parameterColumn.getTable());
            if(parameterColumnByTable == null){
                parameterColumnByTable = new ArrayList<>();
            }
            parameterColumnByTable.add("`" + parameterColumn.getColumn() + "`");//避免关键字
            returnMap.put(parameterColumn.getTable(),parameterColumnByTable);
        }
        return returnMap;
    }

    /**
     * 获取全部表需要传输的字段
     * @return
     */
    public Map<String, List<String>> getSelectUpdateColumns(){
        Map<String, List<String>> returnMap = new HashMap<>();
        //返回数据
        List<MaInvsDataExchangeParameterColumnEntity> parameterColumnList = parameterColumnMapper.selectUpdateColumn();
        //对返回数据进行数据格式处理，方便后续循环判断
        for(MaInvsDataExchangeParameterColumnEntity parameterColumn:parameterColumnList){
            List<String> parameterColumnByTable = returnMap.get(parameterColumn.getTable());
            if(parameterColumnByTable == null){
                parameterColumnByTable = new ArrayList<>();
            }
            parameterColumnByTable.add("`" + parameterColumn.getColumn() + "`");//避免关键字
            returnMap.put(parameterColumn.getTable(),parameterColumnByTable);
        }
        return returnMap;
    }



    /**
     * 特殊表特殊字段处理
     * @param tableName
     * @param list
     * @return
     */
    public List<Map<String,Object>> specialColumn(String tableName,List<Map<String,Object>> list,Map<String,
            List<MaInvsDataExchangeSpecialDataEntity>> specialDatas,String accessUrl){
        //判断当前表是否存在处理数据
        List<MaInvsDataExchangeSpecialDataEntity> specialDataList = specialDatas.get(tableName);
        if(specialDataList != null && specialDataList.size() > 0){
            //遍历需要处理的字段
            for(MaInvsDataExchangeSpecialDataEntity specialData:specialDataList){
                //遍历需要处理的数据
                for(Map<String,Object> map:list){
                    try {
                        if("1".equals(specialData.getType())){//处理方式 1：OssUrl地址转base64
                            Object Obj = map.get(specialData.getColumn());
                            if(Obj != null && Obj instanceof String){
                                String base64 = AliCloudOssUtil.getBase64ByUrl(null, Obj.toString());
                                map.put(specialData.getColumn(),"data:image/png;base64," + base64);//直接拼接【data:image/png;base64,】可以前端不做调整
                            }
                        }else if("2".equals(specialData.getType())){//处理方式 2:关联图片表传递图片表数据
                            Object Obj = map.get(specialData.getColumn());
                            if(Obj != null && Obj instanceof String && !"".equals(Obj)){
                                String[] imgIds = Obj.toString().split(",");
                                //查询图片表数据
                                AllTypesTableEntity entity = new AllTypesTableEntity();
                                entity.setIds(Arrays.asList(imgIds));
                                List<Map<String, Object>> imgList = allTypesTableMapper.selectImgs(entity);
                                //base64转码
                                for(Map<String, Object> img:imgList){
                                    Object path = img.get("path");
                                    if(path != null && path instanceof String){
                                        String base64 = AliCloudOssUtil.getBase64ByUrl(null, path.toString());
                                        img.put("path","data:image/png;base64," + base64);//直接拼接【data:image/png;base64,】可以前端不做调整
                                    }
                                }
                                //处理时间格式数据
                                imgList = timeFormat(imgList);
                                //请求接口
                                JSONObject resultJson = HttpClientUtil.sendPost2("dd_picture", imgList, accessUrl);
                                //获取接口返回参数判断状态
                                if(resultJson != null && resultJson.get("errcode") != null && "0".equals(resultJson.get("errcode"))){
                                    //如果存在失败数据
                                    if(resultJson.get("errorIds") != null && resultJson.get("errorIds") instanceof List<?>){
                                        List<Object> errorIds = (List<Object>)resultJson.get("errorIds");
                                        if(errorIds.size() > 0){
                                            //判定主数据传输失败【剔除list内map对整体逻辑修改比较大。直接修改这条数据至其传输失败即可】
                                            map.put("error_field_is_not_abnormal","error_value_is_not_abnormal");
                                        }
                                    }
                                }else{
                                    LOGGER.error("dd_picture"+"表传输数据接口请求失败！");
                                }
                            }
                        }
                    }catch (Exception e){
                        String errorMsg = "特殊表特殊字段处理异常！表名："+tableName+"，处理字段："+specialData.getColumn()+"，处理类型："+specialData.getType()+"，处理值："+map.get(specialData.getColumn());
                        StringWriter sw = new StringWriter();
                        e.printStackTrace(new PrintWriter(sw, true));
                        saveErrorMsg(tableName, errorMsg, sw.toString());
                    }
                }
            }
        }
        return list;
    }

    /**
     * 时间格式处理
     */
    public List<Map<String, Object>> timeFormat(List<Map<String, Object>> dataList){
        for(Map<String, Object> data:dataList){
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                if(entry.getValue() instanceof Date){
                    data.put(entry.getKey(),""+entry.getValue());
                }
            }
        }
        return dataList;
    }

    /**
     * 添加错误日志信息
     */
    public void saveErrorMsg(String tableName,String errorMsg,String errorText){
        LOGGER.error(errorMsg);
        MaInvsDataExchangeErrorEntity maInvsDataExchangeErrorEntity = new MaInvsDataExchangeErrorEntity();
        maInvsDataExchangeErrorEntity.setTableName(tableName);
        maInvsDataExchangeErrorEntity.setErrorMsg(errorMsg);
        maInvsDataExchangeErrorEntity.setErrorText(errorText);
        maInvsDataExchangeErrorEntity.setCreateTime(new Date());
        exchangeErrorMapper.insert(maInvsDataExchangeErrorEntity);
    }


    /**
     * 请求接口(测试方法)
     */
    public Map<String,Object> testCon(String tableName, List<Map<String,Object>> list){
        Map<String, Object> resultMap = new HashMap<>();
        try {
            Map<String, List<Object>> serviceResultMap = dataFromInvsWebService.saveAllTypesList(tableName, list);
            //处理service返回数据
            resultMap.put("completeIds",serviceResultMap.get("completeIds"));//完成ID集合
            resultMap.put("errorIds",serviceResultMap.get("errorIds"));//错误ID集合
            resultMap.put("errcode","0");//请求成功
        }catch (Exception e){
            resultMap.put("errcode","-1");
            resultMap.put("msg","接口请求异常！" + e.getMessage());
        }
        return resultMap;
    }

}